<?php
/**
 * 拍卖房间相关接口
 */

namespace App\Http\Controllers\App\V3;

use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;

class AuctionController extends BaseController
{
    public function set()
    {
        $content_list = app('model_auction_content')->getAllContent();
        $gift_list = app('model_auction_gift')->orderBy('sort', 'asc')->orderBy('gift_price', 'asc')->orderBy('id', 'asc')->get();
        $time_list = app('model_auction_time')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();

        return Response::sendData([
            'content_list' => $content_list,
            'gift_list'    => $gift_list,
            'time_list'    => $time_list,
        ]);
    }

    public function start(Request $request)
    {
        $room_id = $request->input('room_id');
        $content = $request->input('content');                             //拍卖内容
        $content_type = $request->input('content_type', 1);                //拍卖内容类型 1默认2自定义
        $auction_gift_id = $request->input('auction_gift_id');             //起拍礼物id
        $time_id = $request->input('time_id');                             //拍卖时间id
        if ($room_id <= 0 || $auction_gift_id <= 0 || $time_id <= 0) {
            throw new BasicException(10010);
        }
        $result = app('repo_auction')->start($room_id, $content, $content_type, $auction_gift_id, $time_id);

        return Response::sendData($result);
    }

    public function offer(Request $request)
    {
        $auction_id = $request->input('auction_id');
        $number = $request->input('number');
        if ($auction_id <= 0) {
            throw new BasicException(10010);
        }
        if (!in_array($number, [1, 5, 10])) {
            throw new BasicException(10010);
        }

        //防止拍卖结束过程中有人再报价
        $end_key = 'auction:end:'.$auction_id;
        if (app('redis')->exists($end_key)) {
            throw new BasicException(40040);
        }

        //防止并发
        $lock_key = 'auction:lock:'.$auction_id;
        if (!lockApi($lock_key, 1000)) {
            throw new BasicException(40082);
        }

        $result = app('repo_auction')->offer($auction_id, $number);

        unlockApi($lock_key);

        return Response::sendData($result);
    }

    public function end(Request $request)
    {
        $auction_id = $request->input('auction_id');
        if ($auction_id <= 0) {
            throw new BasicException(10010);
        }
        $end_key = 'auction:end:'.$auction_id;
        if (!lockApi($end_key)) {
            throw new BasicException(40082);
        }
        $result = app('repo_auction')->end($auction_id);
        app('redis')->del($end_key);

        return Response::sendData($result);
    }
}
